package com.dream.testtubebaby_doctor;

import java.util.Calendar;
import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.dream.testtubebaby_doctor.data.user.UserInfo;
import com.dream.testtubebaby_doctor.fragment.InputDialogFragment;
import com.dream.testtubebaby_doctor.okhttp.OkHttpClientManager;
import com.dream.testtubebaby_doctor.utils.SharePreferencesManager;
import com.dream.testtubebaby_doctor.utils.StatusBarCompat;
import com.dream.testtubebaby_doctor.utils.ToastUtil;
import com.squareup.okhttp.Request;

public class MyAccountActivity extends Activity implements
		InputDialogFragment.OnFragmentInteractionListener {
	private ImageView mBackTextView;
	private TextView user_info_name;
	private TextView user_info_phone;
	private TextView user_info_job;
	private TextView user_info_desc;
	private TextView user_info_fullname;
	private TextView user_info_date;
	private TextView user_info_gender;
	private Button save_user_info_ok;
	private SharePreferencesManager mSharePreferencesManager;
	private int select_gender = 0;
	private ProgressDialog mProgressDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.user_account_view);
		StatusBarCompat.compat(this,
				getResources().getColor(R.color.status_bar_color));
		mSharePreferencesManager = new SharePreferencesManager(this);
		initView();
		mProgressDialog = new ProgressDialog(this);
		mProgressDialog.setMessage(getResources().getString(
				R.string.user_update_photo_msg));
	}

	@Override
	protected void onStart() {
		super.onStart();
		updateUserInfoData();
	}

	private void initView() {
		mBackTextView = (ImageView) findViewById(R.id.back);
		mBackTextView.setOnClickListener(mListener);
		user_info_name = (TextView) findViewById(R.id.user_info_name);
		user_info_phone = (TextView) findViewById(R.id.user_info_phone);
		user_info_job = (TextView) findViewById(R.id.user_info_job);
		user_info_desc = (TextView) findViewById(R.id.user_info_desc);
		user_info_fullname = (TextView) findViewById(R.id.user_info_fullname);
		user_info_date = (TextView) findViewById(R.id.user_info_date);
		user_info_gender = (TextView) findViewById(R.id.user_info_gender);

		RelativeLayout user_info_password_layout = (RelativeLayout) findViewById(R.id.user_info_password_layout);
		user_info_password_layout.setOnClickListener(mListener);
		RelativeLayout user_info_job_layout = (RelativeLayout) findViewById(R.id.user_info_job_layout);
		user_info_job_layout.setOnClickListener(mListener);
		RelativeLayout user_info_desc_layout = (RelativeLayout) findViewById(R.id.user_info_desc_layout);
		user_info_desc_layout.setOnClickListener(mListener);
		RelativeLayout user_info_fullname_layout = (RelativeLayout) findViewById(R.id.user_info_fullname_layout);
		user_info_fullname_layout.setOnClickListener(mListener);
		RelativeLayout user_info_date_layout = (RelativeLayout) findViewById(R.id.user_info_date_layout);
		user_info_date_layout.setOnClickListener(mListener);
		RelativeLayout user_info_gender_layout = (RelativeLayout) findViewById(R.id.user_info_gender_layout);
//		user_info_gender_layout.setOnClickListener(mListener);
		save_user_info_ok = (Button) findViewById(R.id.save_user_info_ok);
		save_user_info_ok.setOnClickListener(mListener);
	}

	OnClickListener mListener = new OnClickListener() {
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.back:
				finish();
				break;

			case R.id.user_info_password_layout: {
				Intent intent = new Intent(MyAccountActivity.this,
						ModifyPasswordActivity.class);
				startActivity(intent);
			}
				break;
			case R.id.user_info_job_layout: {
				InputDialogFragment inputDialogFragment = InputDialogFragment
						.newInstance(
								v.getId(),
								getResources().getString(
										R.string.user_info_title_title),
								user_info_job.getText().toString());
				inputDialogFragment.setListener(MyAccountActivity.this);
				inputDialogFragment.show(getFragmentManager(), "");
			}
				break;
			case R.id.user_info_desc_layout: {
				InputDialogFragment inputDialogFragment = InputDialogFragment
						.newInstance(
								v.getId(),
								getResources().getString(
										R.string.user_info_descrip_title),
								user_info_desc.getText().toString());
				inputDialogFragment.setListener(MyAccountActivity.this);
				inputDialogFragment.show(getFragmentManager(), "");
			}
				break;
			case R.id.user_info_fullname_layout: {
				InputDialogFragment inputDialogFragment = InputDialogFragment
						.newInstance(
								v.getId(),
								getResources().getString(
										R.string.user_info_fullname_title),
								user_info_fullname.getText().toString());
				inputDialogFragment.setListener(MyAccountActivity.this);
				inputDialogFragment.show(getFragmentManager(), "");
			}
				break;
			case R.id.user_info_date_layout: {
				showDatePickerDialog();
			}
				break;
			case R.id.user_info_gender_layout: {
				AlertDialog.Builder builder = new Builder(
						MyAccountActivity.this);
				String[] select = getResources().getStringArray(
						R.array.gender_select);
				builder.setSingleChoiceItems(select, select_gender,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								select_gender = which;
								dialog.dismiss();
								updateGenderView();
							}
						});
				builder.create().show();
			}
				break;
			case R.id.save_user_info_ok: {
				modifyUserInfoUpdate();
			}
				break;
			}
		}
	};

	private void showDatePickerDialog() {
		Calendar c = Calendar.getInstance();
		int year = c.get(Calendar.YEAR);
		int monthOfYear = c.get(Calendar.MONTH);
		int dayOfMonth = c.get(Calendar.DAY_OF_MONTH);
		DatePickerDialog datePickerDialog = new DatePickerDialog(this,
				new OnDateSetListener() {

					@Override
					public void onDateSet(DatePicker view, int year,
							int monthOfYear, int dayOfMonth) {
						StringBuilder stringBuilder = new StringBuilder();
						stringBuilder.append(year).append("/")
								.append(monthOfYear + 1).append("/")
								.append(dayOfMonth);
						user_info_date.setText(stringBuilder.toString());
						save_user_info_ok.setVisibility(View.VISIBLE);
					}
				}, year, monthOfYear, dayOfMonth);
		datePickerDialog.show();
	}

	protected void updateView(UserInfo mUserInfo) {
		user_info_name.setText(mUserInfo.getLogname());
		user_info_phone.setText(mUserInfo.getTelephone());
		user_info_job.setText(mUserInfo.getTitle());
		user_info_desc.setText(mUserInfo.getDescrip());
		user_info_fullname.setText(mUserInfo.getTruename());
		user_info_date.setText("" + mUserInfo.getBirthday());
		if (mUserInfo.getSex() == 0)
			user_info_gender.setText(R.string.user_female);
		else
			user_info_gender.setText(R.string.user_male);
	}

	private void updateGenderView() {
		if (select_gender == 0)
			user_info_gender.setText(R.string.user_female);
		else
			user_info_gender.setText(R.string.user_male);
		save_user_info_ok.setVisibility(View.VISIBLE);
	}

	@Override
	public void onFragmentInteraction(String text, int id) {
		switch (id) {
		case R.id.user_info_job_layout:
			user_info_job.setText(text);
			break;
		case R.id.user_info_desc_layout:
			user_info_desc.setText(text);
			break;
		case R.id.user_info_fullname_layout:
			user_info_fullname.setText(text);
			break;
		default:
			break;
		}
		save_user_info_ok.setVisibility(View.VISIBLE);
	}

	private void updateUserInfoData() {
		long uid = mSharePreferencesManager.readUserId();
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("uid", String.valueOf(uid));
		OkHttpClientManager.postAsyn(OkHttpClientManager.BASEURL
				+ "m=Home&c=App&a=getAccountDetail",
				new OkHttpClientManager.ResultCallback<String>() {

					@Override
					public void onError(Request request, Exception e) {
						ToastUtil.toast(MyAccountActivity.this,
								R.string.server_error);
					}

					// {"result":0,"Account":{"id":"35","truename":null,"telephone":"18317120821","register_time":"1444716766","avatar":"0","image":null,
					// "birthday":"1970","sex":"0","logname":"wuliqing"}}
					@Override
					public void onResponse(String response) {
						try {
							JSONObject obj = new JSONObject(response);
							if (obj != null) {
								int result = obj.getInt("result");
								if (result == 0) {
									JSONObject jsonObj = new JSONObject(obj
											.getString("Account"));
									UserInfo mUserInfo = UserInfo
											.getJsonObject(jsonObj);
									select_gender = mUserInfo.getSex();
									updateView(mUserInfo);
								} else {
									ToastUtil.toast(MyAccountActivity.this,
											R.string.server_error);
								}
							}
						} catch (JSONException e) {
							ToastUtil.toast(MyAccountActivity.this,
									e.toString());
						}
					}
				}, params);
	}

	private void modifyUserInfoUpdate() {
		mProgressDialog.show();
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("uid", String.valueOf(mSharePreferencesManager.readUserId()));
		params.put("truename", user_info_fullname.getText().toString());
		params.put("birthday", user_info_date.getText().toString());
		params.put("sex", String.valueOf(select_gender));
		params.put("descrip", user_info_desc.getText().toString());
		params.put("title", user_info_job.getText().toString());
		OkHttpClientManager.postAsyn(OkHttpClientManager.BASEURL
				+ "m=Home&c=App&a=ModifyAccountDetail",
				new OkHttpClientManager.ResultCallback<String>() {

					@Override
					public void onError(Request request, Exception e) {
						ToastUtil.toast(MyAccountActivity.this,
								R.string.server_error);
						mProgressDialog.dismiss();
					}

					@Override
					public void onResponse(String response) {// {"result":0,"Account":1}
						try {
							JSONObject obj = new JSONObject(response);
							if (obj != null) {
								int result = obj.getInt("result");
								int account = obj.getInt("Account");
								if (result == 0 && account == 1) {
									ToastUtil
											.toast(MyAccountActivity.this,
													R.string.user_info_save_success_msg);
									finish();
								} else {
									finish();
								}
							}
						} catch (JSONException e) {
							ToastUtil.toast(MyAccountActivity.this,
									e.toString());
						}
						mProgressDialog.dismiss();
					}
				}, params);
	}
}
